<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>sse demo</title>
</head>
<body>
<div id="con"></div>
<script>
    let chat = document.getElementById("con");
    if (window.EventSource) {
        // 创建sse
        eventSource = new EventSource('http://localhost:8080/demo');
        eventSource.onopen = function (event) {
            chat.innerHTML += 'SSE链接成功' + '<br/><br/>';
        }
        eventSource.onmessage = function (event) {
            if (event.data) {
                chat.innerHTML += '接收到数据：' + event.data + '<br/><br/>';
            }
        }
        eventSource.onerror = (error) => {
            chat.innerHTML += '发生异常' + error.message + '<br/><br/>';
            //eventSource.close(); // 可以选择在发生错误时关闭连接
        };
    } else {
        alert("你的浏览器不支持SSE");
    }

    function closeEventSource() {
        if (eventSource) {
            eventSource.close();
            console.log('EventSource connection closed.');
        }
    }
</script>
<button id="closeButton" onclick="closeEventSource()">客户端主动关闭连接</button>
</body>
</html>